<template>
    <div class="main_container" style="background: #f5f5f5;">
        <div class="top">
            <i class="el-icon-s-custom"></i>
            <span>个人中心</span>
        </div>
        <div class="user_info">
            <el-row>
                <el-col :span="5">
                    <div class="avatar">
                        <div class="pics">
                            <el-upload action="anything" 
                                :http-request="(params) => uploadSectionFile(params, 'picUpload')" 
                                :show-file-list="false" 
                                :accept="picUpload.accept.join(',')">
                                <img :src="userInfo.avatar" alt="">
                            </el-upload>
                            <div class="camera">
                                <i class="el-icon-camera"></i>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="18">
                    <div class="tag_view">
                        <div class="item">
                            <span>用户名：</span>
                            <span>{{userInfo.username}}</span>
                        </div>
                        <div class="item">
                            <span>手机号码：</span>
                            <span>{{userInfo.phone}}</span>
                        </div>
                        <div class="item">
                            <span>邮箱：</span>
                            <span>{{userInfo.email}}</span>
                        </div>
                        <div class="item">
                            <span>联系地址：</span>
                            <span>{{userInfo.user_address}}</span>
                        </div>
                        <div class="item">
                            <span>注册时间：</span>
                            <span>{{userInfo.register_time}}</span>
                        </div>
                        <div class="item">
                            <span>到期时间：</span>
                            <span>{{userInfo.expire_time}}</span>
                        </div>
                        <div class="item">
                            <span>密码：</span>
                            <span>已设置</span>
                            <span class="btn" @click="showChangePwd=true">修改</span>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
        <div class="update_view">
            <el-tabs type="border-card" style="height: 100%;">
                <el-tab-pane label="基础信息">
                    <div class="form_view">
                        <el-form label-position="top" :model="formData">
                            <el-form-item label="用户名">
                                <el-input v-model="formData.username" placeholder="请输入" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱">
                                <el-input v-model="formData.email" placeholder="请输入" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="联系地址">
                                <el-input v-model="formData.user_address" placeholder="请输入" clearable></el-input>
                            </el-form-item>
                        </el-form>
                        <div class="btn_view">
                            <div class="btn sure" @click="editUserInfo">保存</div>
                            <div class="btn" @click="resetForm('userInfo')">重置</div>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane v-if="isAdmin" label="企业信息">
                    <div class="form_view">
                        <el-form label-position="top" :model="formData">
                            <el-form-item label="企业名称">
                                <el-input v-model="formData.corp_name" placeholder="请输入" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="企业简称">
                                <el-input v-model="formData.abbr_name" placeholder="请输入" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="地址">
                                <el-input v-model="formData.address" placeholder="请输入" clearable></el-input>
                            </el-form-item>
                        </el-form>
                        <div class="btn_view">
                            <div class="btn sure" @click="editCompany">保存</div>
                            <div class="btn" @click="resetForm('company')">重置</div>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <el-dialog width="30%" title="修改密码" center :visible.sync="showChangePwd" append-to-body>
			<div>
				<el-form ref="pwdForm" :model="pwdForm" :rules="pwdRules" label-width="auto">
                    <el-row>
                        <el-form-item label="旧密码" prop="oldPassword">
                            <el-input style="width: 240px;" v-model="pwdForm.oldPassword" placeholder="请输入" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="新密码" prop="password">
                            <el-input style="width: 240px;" v-model="pwdForm.password" placeholder="请输入" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="确认密码" prop="repeatPassword">
                            <el-input style="width: 240px;" v-model="pwdForm.repeatPassword" placeholder="请输入" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-row>
                </el-form>
			</div>
			<span slot="footer" class="dialog-footer">
                <el-button size="small" @click="resetForm('pwd')">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="commitPwd">确 定</el-button>
            </span>
		</el-dialog>
    </div>
</template>

<script>
	import { uploadFiles } from '@/api/unicloudApi'
	import { fileUpload, updateCompany, updateUserInfo, updatePassWord } from '@/api/user'
    export default {
		data() {
			return {
                corp_id: '',
                isAdmin: false,
                showChangePwd: false,
                picUpload: {
                    max: 5,
                    accept: ['.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', '.BMP']
                },
                userInfo: {
                    avatar: '',
					username: '',
					email: '',
                    user_address: '',  //用户地址
                    phone: '',
                    register_time: '',
                    expire_time: ''
                },
                formData: {
                    image_id: '',
					username: '',
					email: '',
                    user_address: '',  //用户地址
					corp_name: '',
					abbr_name: '',
					address: '',  //企业地址
                },
                pwdForm: {
					oldPassword: '',
					password: '',
					repeatPassword: '',
					corp_id: ''
                },
                pwdRules: {
                    oldPassword: [
                        { required: true, message: "请输入旧密码", trigger: "blur" },
                    ],
                    password: [
                        { required: true, message: "请输入新密码", trigger: "blur" },
                    ],
                    repeatPassword: [
                        { required: true, message: "请输入确认密码", trigger: "blur" },
                    ]
                }
			}
		},
 		computed: {
		},
		mounted() {
            this.corp_id = this.$store.state.corpId
            this.isAdmin = this.$store.state.isAdmin
            // 获取当前登录用户信息
            this.getUserInfo()
		},
		methods: {
            // 上传前校验
            beforeUpload (file, uploadType) {
                let isRightSize = file.size / 1024 / 1024 < this[uploadType].max
                if (!isRightSize) {
                    this.$message.error('文件大小超过' + this[uploadType].max + 'MB')
                }
                let fileArr = file.name.split('.')
                let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + fileArr[fileArr.length - 1])
                if (!isAccept) {
                    this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
                }
                return isRightSize && isAccept
            },
            // 附件上传
            uploadSectionFile (params, uploadType) {
                let _this = this
                if (!this.beforeUpload(params.file, uploadType)) {
                    params.onError()
                    return
                }
                
                let name = params.file.name.split('.')
                let file_ext = name[name.length-1]
                const reader = new FileReader();
                // 定义读取完成后的处理逻辑
                reader.onload = (e) => {
                    // e.target.result 是文件的内容，这里是 ArrayBuffer
                    const arrayBuffer = e.target.result;
                    const buffer = Buffer.from(arrayBuffer); // 转换为 Buffer

                    // 将 Buffer 转换为 Base64 字符串
                    const path = buffer.toString('base64');

                    uploadFiles({ file_ext, path }).then(res => {
                        _this.userInfo.avatar = res.data.fileID
                        // 调用我们的上传接口,获取image_id
                        fileUpload({
                            fileId: res.data.fileID,
                            requestId: '',
                            url: res.data.fileID,
                            corp_id: _this.corp_id
                        }).then(res => {
                            _this.formData.image_id = res.data.id || ''
                            // 修改个人信息
                            _this.editUserInfo()
                        })
                    })
                    // 这里可以进行其他操作，比如展示或上传 blob
                };
                // 定义读取错误后的处理逻辑
                reader.onerror = (error) => {
                    console.error('File reading error:', error);
                };
                // 读取文件内容为 ArrayBuffer
                reader.readAsArrayBuffer(params.file);
            },
            // 获取当前登录用户信息
            getUserInfo() {
                this.userInfo.avatar = this.$store.state.avatar
                this.userInfo.username = this.$store.state.userInfo.username
                this.userInfo.email = this.$store.state.userInfo.email || ''
                this.userInfo.user_address = this.$store.state.userInfo.address
                this.userInfo.phone = this.$store.state.userInfo.phone_no
                this.userInfo.register_time = this.$store.state.userInfo.create_time.substring(0, 10)
                this.userInfo.expire_time = this.$store.state.userInfo.corp_info.expire_time_show.substring(0, 10)

                this.formData.image_id = this.$store.state.userInfo.image || ''
                this.formData.username = this.$store.state.userInfo.username
                this.formData.email = this.$store.state.userInfo.email || ''
                this.formData.user_address = this.$store.state.userInfo.address
                this.formData.address = this.$store.state.userInfo.corp_info.address
                this.formData.corp_name = this.$store.state.userInfo.corp_info.corp_name
                this.formData.abbr_name = this.$store.state.userInfo.corp_info.abbr_name
            },
            // 更新个人信息
            editUserInfo() {
                updateUserInfo({
					image_id: this.formData.image_id,
					username: this.formData.username,
					email: this.formData.email,
					corp_id: this.corp_id,
                    address: this.formData.user_address
                }).then(res => {
                    if (res.code == 200){
                        this.$message({
                            message: "修改成功",
                            type: "success",
                        })
                        setTimeout(() => {
                            location.reload()
                        }, 1000);
                    }
                })
            },
            // 更新企业信息
            editCompany() {
                updateCompany({
                    id: this.corp_id,
                    corp_name: this.formData.corp_name,
                    abbr_name: this.formData.abbr_name,
                    address: this.formData.address
                }).then(res => {
                    if (res.code == 200){
                        this.$message({
                            message: "修改成功",
                            type: "success",
                        })
                        setTimeout(() => {
                            location.reload()
                        }, 1000);
                    }
                })
            },
            // 表单重置
            resetForm(type) {
                if (type == 'userInfo'){
                    this.formData.username = ''
                    this.formData.email = ''
                    this.formData.user_address = ''
                }else if (type == 'company'){
                    this.formData.address = ''
                    this.formData.abbr_name = ''
                    this.formData.corp_name = ''
                }else if (type == 'pwd'){
                    this.pwdForm.password = ''
                    this.pwdForm.oldPassword = ''
                    this.pwdForm.repeatPassword = ''
                    this.showChangePwd = false
                }
            },
            commitPwd() {
                var that = this
                that.$refs['pwdForm'].validate(valid => {
                    if(!valid) return

                    let { flag, msg } = that.checkRules()
                    if (flag){
                        that.$message.error(msg)
                        return
                    }
                    
                    that.pwdForm.corp_id = that.corp_id
                    updatePassWord(that.pwdForm).then(res => {
                        if (res.code == 200){
                        that.$message({
                            message: "修改成功",
                            type: "success",
                        })
                        setTimeout(() => {
                            location.reload()
                        }, 1000);
                    }
                    })
                })
            },
            checkRules() {
                let reg = /^[A-Za-z\d@$!%*?&#_]{6,}$/
				let flag = false, msg = ''
				if (!reg.test(this.pwdForm.password)){
                    flag = true
                    msg = '密码长度至少6位数且只能包含字母、数字和特殊符号'
                }else if(this.pwdForm.password != this.pwdForm.repeatPassword){
                    flag = true
                    msg = '两次密码输入不一致，请重新输入'
                }
                return {flag, msg}
            }
		}
    }
</script>

<style lang="less" scoped>
	@import '../../style/mixin';
    .top {
        height: 30px;
        line-height: 30px;
        display: flex;
        align-items: center;
        i {
            color: @blue;
            font-size: 20px;
        }
        span {
            font-size: 15px;
            font-weight: bold;
            color: #333;
            margin-left: 8px;
        }
    }
    .user_info {
        background: #fff;
        height: 180px;
        margin-top: 10px;
        .avatar {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 180px;
            .pics {
                position: relative;
                width: 100px;
                height: 100px;
                img {
                    width: 100px;
                    height: 100px;
                    border-radius: 50px;
                    &:hover{
                        cursor: pointer;
                    }
                }
                .camera {
                    position: absolute;
                    width: 30px;
                    height: 30px;
                    line-height: 30px;
                    text-align: center;
                    border-radius: 15px;
                    border: 1px solid #fff;
                    background: #eee;
                    top: 65px;
                    right: 5px;
                    i {
                        color: @blue;
                        font-size: 18px;
                    }
                }
            }
        }
        .tag_view {
            display: flex;
            flex-wrap: wrap;
            width: 100%;
            height: 120px;
            align-items: center;
            padding: 30px 0;
            .item {
                font-size: 14px;
                color: #333;
                width: 33.33%;
                .btn {
                    margin-left: 20px;
                    cursor: pointer;
                    color: @blue;
                }
            }
        }
    }
    .update_view {
        margin-top: 20px;
        width: 100%;
        height: ~"calc(100% - 250px)";
        background: #fff;
        .form_view {
            width: 50%;
            padding: 20px 0 0 20px;
            .btn_view {
                margin-top: 20px;
                height: 40px;
                display: flex;
                align-items: center;
                .btn {
                    width: 80px;
                    height: 35px;
                    line-height: 35px;
                    text-align: center;
                    background: #ccc;
                    font-size: 14px;
                    border-radius: 3px;
                    color: #333;
                    &:hover{
                        cursor: pointer;
                    }
                }
                .sure {
                    color: #fff;
                    background: @blue;
                    margin-right: 30px;
                }
            }
        }
    }
</style>